package com.atguigu.gmall.list.listener;


import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.ListService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ListenerUpdateEs {

    @Autowired
    ListService listService;

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(name = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = MqConst.ROUTING_GOODS_UPPER
    )})
    public void UpdateEs(Long skuId, Message message, Channel channel){

        try {
            listService.upperGoods(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            if (!message.getMessageProperties().isRedelivered()){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }else {
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(name = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    )})
    public void DeleteEs(Long skuId, Message message, Channel channel){

        try {
            listService.lowerGoods(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            if (!message.getMessageProperties().isRedelivered()){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }else {
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
